import { ref, reactive, computed } from 'vue'
import api from '@/api/http'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getToken } from '@/utils/auth'

// Utility to build SSE base url (compatible with dev proxy)
function resolveApiBase() {
  const origin = window.location.origin
  const base = api?.defaults?.baseURL || '/api'
  if (base.startsWith('http')) return base
  return origin.replace(/\/$/, '') + base
}

export function useChatSessions() {
  const sessions = ref([])
  const currentSessionId = ref(null)
  const messages = ref([])
  const streamingBuffer = ref('')
  const streaming = ref(false)
  const inputDisabled = computed(() => streaming.value || loading.send)

  const loading = reactive({
    list: false,
    create: false,
    messages: false,
    send: false,
    rename: false,
    delete: false,
    clear: false,
  })

  const currentSession = computed(() => sessions.value.find(s => s.id === currentSessionId.value) || null)

  async function loadSessions() {
    if (loading.list) return
    loading.list = true
    try {
  const resp = await api.get('/api/chat/sessions')
      sessions.value = resp.data.sessions || []
    } catch (e) { /* global interceptor handles */ } finally { loading.list = false }
  }

  async function createSession(extra = {}) {
    loading.create = true
    try {
      const payload = Object.assign({ title: '' }, extra)
  const resp = await api.post('/api/chat/sessions', payload)
      const s = resp.data
      sessions.value.unshift(s)
      selectSession(s.id)
      // 再拉全量保证字段一致
      loadSessions()
      ElMessage.success('会话创建成功')
      return s
    } catch (e) {} finally { loading.create = false }
  }

  async function createSessionAndSend(firstContent, extra = {}) {
    // interpret 情况：若已存在一个 interpret 且 message_count==0 的会话，直接复用
    if (extra.meta && extra.meta.purpose === 'interpret') {
      const existing = sessions.value.find(s => s.meta && s.meta.purpose === 'interpret' && (s.message_count === 0))
      if (existing) {
        selectSession(existing.id)
        if (firstContent) await sendMessage(firstContent)
        return existing
      }
    }
    const s = await createSession(extra)
    if (s && firstContent) {
      // 等待会话选中后发送
      await sendMessage(firstContent)
    }
    return s
  }

  function selectSession(id) {
    if (currentSessionId.value === id) return
    currentSessionId.value = id
    messages.value = []
    streamingBuffer.value = ''
    fetchMessages(id)
  }

  async function fetchMessages(id, opts = {}) {
    if (!id) return
    loading.messages = true
    try {
    const resp = await api.get(`/api/chat/sessions/${id}/messages`)
      messages.value = resp.data.messages || []
    } catch (e) {} finally { loading.messages = false }
  }

  async function renameSession(id, title) {
    loading.rename = true
    try {
  const resp = await api.patch(`/api/chat/sessions/${id}`, { title })
      const idx = sessions.value.findIndex(s => s.id === id)
      if (idx !== -1) sessions.value[idx] = resp.data
      ElMessage.success('重命名成功')
    } catch (e) {
      ElMessage.error('重命名失败')
    } finally { loading.rename = false }
  }

  async function updateSessionMode(id, mode) {
    if (!id) return
    loading.rename = true
    try {
      // 仅更新 meta.mode，后端会基于 mode 选择相应的 system_prompt
      const resp = await api.patch(`/api/chat/sessions/${id}`, { meta: { mode } })
      // 兜底：确保本地 meta.mode 与本次选择一致，防止后端未返回最新 meta
      const updated = resp.data || {}
      if (!updated.meta) updated.meta = {}
      updated.meta.mode = mode
      const idx = sessions.value.findIndex(s => s.id === id)
      if (idx !== -1) sessions.value[idx] = updated
      ElMessage.success('已切换对话角色')
    } catch (e) {
      ElMessage.error('切换角色失败')
    } finally {
      loading.rename = false
    }
  }

  async function deleteSession(id) {
    try {
  await ElMessageBox.confirm('确定删除该会话以及所有消息？', '删除确认', { type: 'warning', confirmButtonText: '确认', cancelButtonText: '取消' })
    } catch { return }
    loading.delete = true
    try {
  await api.delete(`/api/chat/sessions/${id}`)
      sessions.value = sessions.value.filter(s => s.id !== id)
      if (currentSessionId.value === id) {
        currentSessionId.value = null
        messages.value = []
        streamingBuffer.value = ''
      }
      ElMessage.success('会话已删除')
    } catch (e) {
      ElMessage.error('删除失败')
    } finally { loading.delete = false }
  }

  async function clearMessages(id) {
    try {
  await ElMessageBox.confirm('清空该会话所有消息？', '清空确认', { type: 'warning', confirmButtonText: '确认', cancelButtonText: '取消' })
    } catch { return }
    loading.clear = true
    try {
  await api.delete(`/api/chat/sessions/${id}/messages`)
      if (currentSessionId.value === id) messages.value = []
      const s = sessions.value.find(s => s.id === id)
      if (s) s.message_count = 0
      ElMessage.success('会话已清空')
    } catch (e) {
      ElMessage.error('清空失败')
    } finally { loading.clear = false }
  }

  async function sendMessage(content) {
    if (!currentSessionId.value || !content) return
    loading.send = true
    streaming.value = true
    streamingBuffer.value = ''
    const activeSession = sessions.value.find(s => s.id === currentSessionId.value)
    const currentMode = activeSession?.meta?.mode || 'default'
    const assistantMeta = currentMode && currentMode !== 'default' ? { mode: currentMode } : null
    // 先推入用户消息
    messages.value.push({ id: 'tmp-u-' + Date.now(), role: 'user', content })
    const base = resolveApiBase()
    try {
      const token = getToken()
  const resp = await fetch(`${base}/api/chat/sessions/${currentSessionId.value}/messages`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'text/event-stream',
          ...(token ? { 'Authorization': `Bearer ${token}` } : {})
        },
        body: JSON.stringify({ content, stream: true, mode: currentMode })
      })
      if (!resp.ok || !resp.body) {
        ElMessage.error('流式请求失败'); streaming.value = false; loading.send = false; return
      }
      // 如果此时 sessions 还是空的（可能初始加载由于未登录/延迟导致），尝试重新拉取一次保证侧栏有数据
      if (!sessions.value.length) {
        loadSessions()
      }
      const reader = resp.body.getReader()
      const decoder = new TextDecoder('utf-8')
      let partial = ''
      while (true) {
        const { value, done } = await reader.read()
        if (done) break
        const text = decoder.decode(value, { stream: true })
        partial += text
        const frames = partial.split(/\n\n/)
        partial = frames.pop() || ''
        for (const frame of frames) {
          const line = frame.trim()
          if (!line.startsWith('data:')) continue
            const payload = line.slice(5).trim()
            if (payload === '[DONE]') { partial=''; break }
            if (payload.startsWith('[ERROR]')) { streamingBuffer.value += '\n' + payload; continue }
            streamingBuffer.value += payload
        }
      }
      // 固化 assistant 消息（前端临时展示）
      messages.value.push({ id: 'tmp-a-' + Date.now(), role: 'assistant', content: streamingBuffer.value, meta: assistantMeta })
      // 重要：后端在 user 最终消息 + assistant 最终消息各自 finalize 时已经把 message_count 增加 2
      // 这里不再手动 +2，避免出现翻倍。改为结束后主动同步一次，获取真实 ID / 顺序 / 计数。
      const finishedSessionId = currentSessionId.value
      streamingBuffer.value = ''
      // 异步拉取权威消息列表（不阻塞 UI）
      if (finishedSessionId) {
        fetchMessages(finishedSessionId)
        // 如果这是该会话首轮问答（messages.length 现在应 >=2 且之前可能为1），尝试刷新会话列表获取自动生成标题
        // 这里简单调用 loadSessions（轻量列表接口）
        // 触发刷新条件：首轮（新建）或清空后首轮（messages 很少）
        if (messages.value.filter(m => m.role === 'user' || m.role === 'assistant').length <= 3) {
          loadSessions()
        }
      }
    } catch (e) {
      ElMessage.error('发送失败')
    } finally {
      streaming.value = false
      loading.send = false
    }
  }

  return {
    sessions,
    currentSessionId,
    currentSession,
    messages,
    streaming,
    streamingBuffer,
    loading,
    inputDisabled,
    loadSessions,
  createSession,
  createSessionAndSend,
    selectSession,
    fetchMessages,
    renameSession,
    updateSessionMode,
    deleteSession,
    clearMessages,
    sendMessage,
  }
}
